    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filters;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Barbara
 */
@WebFilter(filterName = "ControleAcessoAluno", urlPatterns = {"/aluno/*"})
public class ControleDeAcessoAluno implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        // Verificando se o login e a senha estão corretos.
        String login = request.getParameter("login");
        String senha = request.getParameter("senha");
        HttpSession session = req.getSession();
        if (login != null && login.equals("aluno") && senha != null && senha.equals("123")) {
            session.setAttribute("aluno", "logado");
        }
        if (req.getRequestURI().indexOf("deslogar.jsp") != -1) {
            session.invalidate();
            req.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            // Verificando se existe usuário na sessão (indicando que ele está logado)
            String user = (String) session.getAttribute("aluno");
            if (user != null && user.trim().length() > 0) {
                chain.doFilter(request, response);
            } else {
                req.setAttribute("action", req.getRequestURI());
                req.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
